<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
	<meta name="keywords" content="Seata" />
	<meta name="description" content="Saga模式是SEATA提供的长事务解决方案，在Saga模式中，业务流程中每个参与者都提交本地事务，当出现某一个参与者失败则补偿前面已经成功的参与者，一阶段正向服务和二阶段补偿服务都由业务开发实现。" />
	<!-- 网页标签标题 -->
	<title>Seata Saga 模式</title>
  <link rel="shortcut icon" href="/img/seata_logo_small.jpeg"/>
	<link rel="stylesheet" href="/build/documentation.css" />
</head>
<body>
	<div id="root"><div class="documentation-page" data-reactroot=""><header class="header-container header-container-normal"><div class="header-body"><a href="/zh-cn/index.html"><img class="logo" src="//img.alicdn.com/tfs/TB1gqL1w4D1gK0jSZFyXXciOVXa-1497-401.png"/></a><div class="search search-normal"><span class="icon-search"></span></div><span class="language-switch language-switch-normal">En</span><div class="header-menu"><img class="header-menu-toggle" src="https://img.alicdn.com/tfs/TB14eEmw7P2gK0jSZPxXXacQpXa-38-32.png"/><ul><li class="menu-item menu-item-normal"><a href="/zh-cn/index.html" target="_self">首页</a></li><li class="menu-item menu-item-normal menu-item-normal-active"><a href="/zh-cn/docs/overview/what-is-seata.html" target="_self">文档</a></li><li class="menu-item menu-item-normal"><a href="/zh-cn/docs/developers/developers_dev.html" target="_self">开发者</a></li><li class="menu-item menu-item-normal"><a href="/zh-cn/blog/index.html" target="_self">博客</a></li><li class="menu-item menu-item-normal"><a href="/zh-cn/community/index.html" target="_self">社区</a></li><li class="menu-item menu-item-normal"><a href="/zh-cn/blog/download.html" target="_self">下载</a></li></ul></div></div></header><div class="bar"><div class="bar-body"><img src="https://img.alicdn.com/tfs/TB1cm8nJwDqK1RjSZSyXXaxEVXa-160-160.png" class="front-img"/><span>文档</span><img src="https://img.alicdn.com/tfs/TB1cm8nJwDqK1RjSZSyXXaxEVXa-160-160.png" class="back-img"/></div></div><section class="content-section"><div class="sidemenu"><div class="sidemenu-toggle"><img src="https://img.alicdn.com/tfs/TB1E6apXHGYBuNjy0FoXXciBFXa-200-200.png"/></div><ul><li class="menu-item menu-item-level-1"><span>概述</span><ul><li style="height:36px;overflow:hidden" class="menu-item menu-item-level-2"><a href="/zh-cn/docs/overview/what-is-seata.html" target="_self">Seata 是什么？</a></li><li style="height:36px;overflow:hidden" class="menu-item menu-item-level-2"><a href="/zh-cn/docs/overview/terminology.html" target="_self">术语表</a></li><li style="height:36px;overflow:hidden" class="menu-item menu-item-level-2"><a href="/zh-cn/docs/overview/faq.html" target="_self">FAQ</a></li></ul></li><li class="menu-item menu-item-level-1"><span>用户文档</span><ul><li style="height:36px;overflow:hidden" class="menu-item menu-item-level-2"><a href="/zh-cn/docs/user/quickstart.html" target="_self">快速启动</a></li><li style="height:36px;overflow:hidden" class="menu-item menu-item-level-2"><a href="/zh-cn/docs/user/configurations.html" target="_self">参数配置</a></li><li style="height:36px;overflow:hidden" class="menu-item menu-item-level-2"><span>事务分组<img style="transform:rotate(-90deg)" class="menu-toggle" src="https://img.alicdn.com/tfs/TB15.Ilw2b2gK0jSZK9XXaEgFXa-26-16.png"/></span><ul><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/user/txgroup/transaction-group.html" target="_self">事务分组介绍</a></li><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/user/txgroup/transaction-group-and-ha.html" target="_self">事务分组与高可用</a></li></ul></li><li style="height:36px;overflow:hidden" class="menu-item menu-item-level-2"><span>配置中心<img style="transform:rotate(-90deg)" class="menu-toggle" src="https://img.alicdn.com/tfs/TB15.Ilw2b2gK0jSZK9XXaEgFXa-26-16.png"/></span><ul><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/user/configuration/index.html" target="_self">简介</a></li><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/user/configuration/nacos.html" target="_self">Nacos 配置中心</a></li><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/user/configuration/apollo.html" target="_self">Apollo 配置中心</a></li><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/user/configuration/etcd3.html" target="_self">Etcd3 配置中心</a></li><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/user/configuration/consul.html" target="_self">Consul 配置中心</a></li><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/user/configuration/zookeeper.html" target="_self">Zookeeper 配置中心</a></li></ul></li><li style="height:36px;overflow:hidden" class="menu-item menu-item-level-2"><span>注册中心<img style="transform:rotate(-90deg)" class="menu-toggle" src="https://img.alicdn.com/tfs/TB15.Ilw2b2gK0jSZK9XXaEgFXa-26-16.png"/></span><ul><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/user/registry/index.html" target="_self">简介</a></li><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/user/registry/nacos.html" target="_self">Nacos 注册中心</a></li><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/user/registry/eureka.html" target="_self">Eureka 注册中心</a></li><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/user/registry/etcd3.html" target="_self">Etcd3 注册中心</a></li><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/user/registry/consul.html" target="_self">Consul 注册中心</a></li><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/user/registry/zookeeper.html" target="_self">Zookeeper 注册中心</a></li></ul></li><li style="height:36px;overflow:hidden" class="menu-item menu-item-level-2"><a href="/zh-cn/docs/user/api.html" target="_self">API 支持</a></li><li style="height:36px;overflow:hidden" class="menu-item menu-item-level-2"><a href="/zh-cn/docs/user/microservice.html" target="_self">微服务框架支持</a></li><li style="height:36px;overflow:hidden" class="menu-item menu-item-level-2"><a href="/zh-cn/docs/user/ormframework.html" target="_self">ORM 框架支持</a></li><li style="height:36px;overflow:hidden" class="menu-item menu-item-level-2"><a href="/zh-cn/docs/user/datasource.html" target="_self">数据库类型支持</a></li><li style="height:36px;overflow:hidden" class="menu-item menu-item-level-2"><span>测试报告<img style="transform:rotate(-90deg)" class="menu-toggle" src="https://img.alicdn.com/tfs/TB15.Ilw2b2gK0jSZK9XXaEgFXa-26-16.png"/></span><ul><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/user/performance.html" target="_self">性能测试报告</a></li></ul></li><li style="height:36px;overflow:hidden" class="menu-item menu-item-level-2"><span>附录<img style="transform:rotate(-90deg)" class="menu-toggle" src="https://img.alicdn.com/tfs/TB15.Ilw2b2gK0jSZK9XXaEgFXa-26-16.png"/></span><ul><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/user/appendix/global-transaction-status.html" target="_self">事务状态</a></li></ul></li></ul></li><li class="menu-item menu-item-level-1"><span>开发者指南</span><ul><li style="height:36px;overflow:hidden" class="menu-item menu-item-level-2"><span>各事务模式<img style="transform:rotate(-90deg)" class="menu-toggle" src="https://img.alicdn.com/tfs/TB15.Ilw2b2gK0jSZK9XXaEgFXa-26-16.png"/></span><ul><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/dev/mode/at-mode.html" target="_self">Seata AT 模式</a></li><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/dev/mode/tcc-mode.html" target="_self">Seata TCC 模式</a></li><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/user/saga.html" target="_self">Seata Saga 模式</a></li><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/dev/mode/xa-mode.html" target="_self">Seata XA 模式</a></li></ul></li><li style="height:36px;overflow:hidden" class="menu-item menu-item-level-2"><a href="/zh-cn/docs/dev/seata-mertics.html" target="_self">Metrics设计</a></li></ul></li><li class="menu-item menu-item-level-1"><span>运维指南</span><ul><li style="height:36px;overflow:hidden" class="menu-item menu-item-level-2"><a href="/zh-cn/docs/ops/upgrade.html" target="_self">版本升级指南</a></li><li style="height:36px;overflow:hidden" class="menu-item menu-item-level-2"><a href="/zh-cn/docs/ops/operation.html" target="_self">Metrics配置</a></li><li style="height:36px;overflow:hidden" class="menu-item menu-item-level-2"><span>部署<img style="transform:rotate(-90deg)" class="menu-toggle" src="https://img.alicdn.com/tfs/TB15.Ilw2b2gK0jSZK9XXaEgFXa-26-16.png"/></span><ul><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/ops/deploy-guide-beginner.html" target="_self">新人文档</a></li><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/ops/deploy-server.html" target="_self">直接部署</a></li><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/ops/deploy-by-docker.html" target="_self">Docker部署</a></li><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/ops/deploy-by-kubernetes.html" target="_self">Kubernetes部署</a></li><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/ops/deploy-by-helm.html" target="_self">Helm 部署</a></li><li class="menu-item menu-item-level-3"><a href="/zh-cn/docs/ops/deploy-ha.html" target="_self">高可用部署</a></li></ul></li></ul></li></ul></div><div class="doc-content markdown-body"><h1>SEATA Saga 模式</h1>
<h2>概述</h2>
<p>Saga模式是SEATA提供的长事务解决方案，在Saga模式中，业务流程中每个参与者都提交本地事务，当出现某一个参与者失败则补偿前面已经成功的参与者，一阶段正向服务和二阶段补偿服务都由业务开发实现。</p>
<p><img src="https://img.alicdn.com/tfs/TB1Y2kuw7T2gK0jSZFkXXcIQFXa-445-444.png" alt="Saga模式示意图"></p>
<p>理论基础：Hector &amp; Kenneth 发表论⽂ Sagas （1987）</p>
<h3>适用场景：</h3>
<ul>
<li>业务流程长、业务流程多</li>
<li>参与者包含其它公司或遗留系统服务，无法提供 TCC 模式要求的三个接口</li>
</ul>
<h3>优势：</h3>
<ul>
<li>一阶段提交本地事务，无锁，高性能</li>
<li>事件驱动架构，参与者可异步执行，高吞吐</li>
<li>补偿服务易于实现</li>
</ul>
<h3>缺点：</h3>
<ul>
<li>不保证隔离性（应对方案见后面文档）</li>
</ul>
<h3>Saga的实现：</h3>
<h4>基于状态机引擎的 Saga 实现：</h4>
<p>目前SEATA提供的Saga模式是基于状态机引擎来实现的，机制是：</p>
<ol>
<li>通过状态图来定义服务调用的流程并生成 json 状态语言定义文件</li>
<li>状态图中一个节点可以是调用一个服务，节点可以配置它的补偿节点</li>
<li>状态图 json 由状态机引擎驱动执行，当出现异常时状态引擎反向执行已成功节点对应的补偿节点将事务回滚</li>
</ol>
<blockquote>
<p>注意: 异常发生时是否进行补偿也可由用户自定义决定</p>
</blockquote>
<ol start="4">
<li>可以实现服务编排需求，支持单项选择、并发、子流程、参数转换、参数映射、服务执行状态判断、异常捕获等功能</li>
</ol>
<p>示例状态图:</p>
<p><img src="/img/saga/demo_statelang.png?raw=true" alt="示例状态图"></p>
<h2>快速开始</h2>
<h3>Demo简介</h3>
<p>基于dubbo构建的微服务下，使用Saga模式演示分布式事务的提交和回滚；</p>
<p>业务流程图如下图所示：</p>
<p><img src="/img/saga/demo_business_process.png?raw=true" alt="demo业务流程图"></p>
<p>先下载seata-samples工程：<a href="https://github.com/seata/seata-samples.git">https://github.com/seata/seata-samples.git</a></p>
<blockquote>
<p>注意SEATA版本需要0.9.0以上</p>
</blockquote>
<p>在dubbo-saga-sample中一个分布式事务内会有2个Saga事务参与者，分别是: <a href="https://github.com/seata/seata-samples/blob/master/saga/dubbo-saga-sample/src/main/java/io/seata/samples/saga/action/InventoryAction.java">InventoryAction</a> 和 <a href="https://github.com/seata/seata-samples/blob/master/saga/dubbo-saga-sample/src/main/java/io/seata/samples/saga/action/BalanceAction.java">BalanceAction</a> ;分布式事务提交则两者均提交，分布式事务回滚则两者均回滚；</p>
<p>这2个Saga参与者均是 dubbo 服务，两个参与都有一个reduce方法，表示库存扣减或余额扣减，还有一个compensateReduce方法，表示补偿扣减操作。</p>
<ul>
<li>InventoryAction 接口定义如下：</li>
</ul>
<pre><code class="language-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">InventoryAction</span> </span>{

    <span class="hljs-comment">/**
     * reduce
     * <span class="hljs-doctag">@param</span> businessKey
     * <span class="hljs-doctag">@param</span> amount
     * <span class="hljs-doctag">@param</span> params
     * <span class="hljs-doctag">@return</span>
     */</span>
    <span class="hljs-function"><span class="hljs-keyword">boolean</span> <span class="hljs-title">reduce</span><span class="hljs-params">(String businessKey, BigDecimal amount, Map&lt;String, Object&gt; params)</span></span>;

    <span class="hljs-comment">/**
     * compensateReduce
     * <span class="hljs-doctag">@param</span> businessKey
     * <span class="hljs-doctag">@param</span> params
     * <span class="hljs-doctag">@return</span>
     */</span>
    <span class="hljs-function"><span class="hljs-keyword">boolean</span> <span class="hljs-title">compensateReduce</span><span class="hljs-params">(String businessKey, Map&lt;String, Object&gt; params)</span></span>;
}
</code></pre>
<ul>
<li>这个场景用状态语言定义就是下面的json：src/main/resources/statelang/reduce_inventory_and_balance.json</li>
</ul>
<pre><code class="language-json">{
    <span class="hljs-attr">"Name"</span>: <span class="hljs-string">"reduceInventoryAndBalance"</span>,
    <span class="hljs-attr">"Comment"</span>: <span class="hljs-string">"reduce inventory then reduce balance in a transaction"</span>,
    <span class="hljs-attr">"StartState"</span>: <span class="hljs-string">"ReduceInventory"</span>,
    <span class="hljs-attr">"Version"</span>: <span class="hljs-string">"0.0.1"</span>,
    <span class="hljs-attr">"States"</span>: {
        <span class="hljs-attr">"ReduceInventory"</span>: {
            <span class="hljs-attr">"Type"</span>: <span class="hljs-string">"ServiceTask"</span>,
            <span class="hljs-attr">"ServiceName"</span>: <span class="hljs-string">"inventoryAction"</span>,
            <span class="hljs-attr">"ServiceMethod"</span>: <span class="hljs-string">"reduce"</span>,
            <span class="hljs-attr">"CompensateState"</span>: <span class="hljs-string">"CompensateReduceInventory"</span>,
            <span class="hljs-attr">"Next"</span>: <span class="hljs-string">"ChoiceState"</span>,
            <span class="hljs-attr">"Input"</span>: [
                <span class="hljs-string">"$.[businessKey]"</span>,
                <span class="hljs-string">"$.[count]"</span>
            ],
            <span class="hljs-attr">"Output"</span>: {
                <span class="hljs-attr">"reduceInventoryResult"</span>: <span class="hljs-string">"$.#root"</span>
            },
            <span class="hljs-attr">"Status"</span>: {
                <span class="hljs-attr">"#root == true"</span>: <span class="hljs-string">"SU"</span>,
                <span class="hljs-attr">"#root == false"</span>: <span class="hljs-string">"FA"</span>,
                <span class="hljs-attr">"$Exception{java.lang.Throwable}"</span>: <span class="hljs-string">"UN"</span>
            }
        },
        <span class="hljs-attr">"ChoiceState"</span>:{
            <span class="hljs-attr">"Type"</span>: <span class="hljs-string">"Choice"</span>,
            <span class="hljs-attr">"Choices"</span>:[
                {
                    <span class="hljs-attr">"Expression"</span>:<span class="hljs-string">"[reduceInventoryResult] == true"</span>,
                    <span class="hljs-attr">"Next"</span>:<span class="hljs-string">"ReduceBalance"</span>
                }
            ],
            <span class="hljs-attr">"Default"</span>:<span class="hljs-string">"Fail"</span>
        },
        <span class="hljs-attr">"ReduceBalance"</span>: {
            <span class="hljs-attr">"Type"</span>: <span class="hljs-string">"ServiceTask"</span>,
            <span class="hljs-attr">"ServiceName"</span>: <span class="hljs-string">"balanceAction"</span>,
            <span class="hljs-attr">"ServiceMethod"</span>: <span class="hljs-string">"reduce"</span>,
            <span class="hljs-attr">"CompensateState"</span>: <span class="hljs-string">"CompensateReduceBalance"</span>,
            <span class="hljs-attr">"Input"</span>: [
                <span class="hljs-string">"$.[businessKey]"</span>,
                <span class="hljs-string">"$.[amount]"</span>,
                {
                    <span class="hljs-attr">"throwException"</span> : <span class="hljs-string">"$.[mockReduceBalanceFail]"</span>
                }
            ],
            <span class="hljs-attr">"Output"</span>: {
                <span class="hljs-attr">"compensateReduceBalanceResult"</span>: <span class="hljs-string">"$.#root"</span>
            },
            <span class="hljs-attr">"Status"</span>: {
                <span class="hljs-attr">"#root == true"</span>: <span class="hljs-string">"SU"</span>,
                <span class="hljs-attr">"#root == false"</span>: <span class="hljs-string">"FA"</span>,
                <span class="hljs-attr">"$Exception{java.lang.Throwable}"</span>: <span class="hljs-string">"UN"</span>
            },
            <span class="hljs-attr">"Catch"</span>: [
                {
                    <span class="hljs-attr">"Exceptions"</span>: [
                        <span class="hljs-string">"java.lang.Throwable"</span>
                    ],
                    <span class="hljs-attr">"Next"</span>: <span class="hljs-string">"CompensationTrigger"</span>
                }
            ],
            <span class="hljs-attr">"Next"</span>: <span class="hljs-string">"Succeed"</span>
        },
        <span class="hljs-attr">"CompensateReduceInventory"</span>: {
            <span class="hljs-attr">"Type"</span>: <span class="hljs-string">"ServiceTask"</span>,
            <span class="hljs-attr">"ServiceName"</span>: <span class="hljs-string">"inventoryAction"</span>,
            <span class="hljs-attr">"ServiceMethod"</span>: <span class="hljs-string">"compensateReduce"</span>,
            <span class="hljs-attr">"Input"</span>: [
                <span class="hljs-string">"$.[businessKey]"</span>
            ]
        },
        <span class="hljs-attr">"CompensateReduceBalance"</span>: {
            <span class="hljs-attr">"Type"</span>: <span class="hljs-string">"ServiceTask"</span>,
            <span class="hljs-attr">"ServiceName"</span>: <span class="hljs-string">"balanceAction"</span>,
            <span class="hljs-attr">"ServiceMethod"</span>: <span class="hljs-string">"compensateReduce"</span>,
            <span class="hljs-attr">"Input"</span>: [
                <span class="hljs-string">"$.[businessKey]"</span>
            ]
        },
        <span class="hljs-attr">"CompensationTrigger"</span>: {
            <span class="hljs-attr">"Type"</span>: <span class="hljs-string">"CompensationTrigger"</span>,
            <span class="hljs-attr">"Next"</span>: <span class="hljs-string">"Fail"</span>
        },
        <span class="hljs-attr">"Succeed"</span>: {
            <span class="hljs-attr">"Type"</span>:<span class="hljs-string">"Succeed"</span>
        },
        <span class="hljs-attr">"Fail"</span>: {
            <span class="hljs-attr">"Type"</span>:<span class="hljs-string">"Fail"</span>,
            <span class="hljs-attr">"ErrorCode"</span>: <span class="hljs-string">"PURCHASE_FAILED"</span>,
            <span class="hljs-attr">"Message"</span>: <span class="hljs-string">"purchase failed"</span>
        }
    }
}
</code></pre>
<p>该json表示的状态图:</p>
<p><img src="/img/saga/demo_statelang.png?raw=true" alt="该json表示的状态图"></p>
<p>状态语言在一定程度上参考了<a href="https://docs.aws.amazon.com/zh_cn/step-functions/latest/dg/tutorial-creating-lambda-state-machine.html">AWS Step Functions</a></p>
<h4>&quot;状态机&quot; 属性简介:</h4>
<ul>
<li>Name: 表示状态机的名称，必须唯一</li>
<li>Comment: 状态机的描述</li>
<li>Version: 状态机定义版本</li>
<li>StartState: 启动时运行的第一个&quot;状态&quot;</li>
<li>States: 状态列表，是一个map结构，key是&quot;状态&quot;的名称，在状态机内必须唯一</li>
</ul>
<h4>&quot;状态&quot; 属性简介:</h4>
<ul>
<li>Type: &quot;状态&quot; 的类型，比如有:
<ul>
<li>ServiceTask: 执行调用服务任务</li>
<li>Choice: 单条件选择路由</li>
<li>CompensationTrigger: 触发补偿流程</li>
<li>Succeed: 状态机正常结束</li>
<li>Fail: 状态机异常结束</li>
<li>SubStateMachine: 调用子状态机</li>
<li>CompensateSubMachine: 用于补偿一个子状态机</li>
</ul>
</li>
<li>ServiceName: 服务名称，通常是服务的beanId</li>
<li>ServiceMethod: 服务方法名称</li>
<li>CompensateState: 该&quot;状态&quot;的补偿&quot;状态&quot;</li>
<li>Input: 调用服务的输入参数列表, 是一个数组, 对应于服务方法的参数列表, $.表示使用表达式从状态机上下文中取参数，表达使用的<a href="https://docs.spring.io/spring/docs/4.3.10.RELEASE/spring-framework-reference/html/expressions.html">SpringEL</a>, 如果是常量直接写值即可</li>
<li>Ouput: 将服务返回的参数赋值到状态机上下文中, 是一个map结构，key为放入到状态机上文时的key（状态机上下文也是一个map），value中$.是表示SpringEL表达式，表示从服务的返回参数中取值，#root表示服务的整个返回参数</li>
<li>Status: 服务执行状态映射，框架定义了三个状态，SU 成功、FA 失败、UN 未知, 我们需要把服务执行的状态映射成这三个状态，帮助框架判断整个事务的一致性，是一个map结构，key是条件表达式，一般是取服务的返回值或抛出的异常进行判断，默认是SpringEL表达式判断服务返回参数，带$Exception{开头表示判断异常类型。value是当这个条件表达式成立时则将服务执行状态映射成这个值</li>
<li>Catch: 捕获到异常后的路由</li>
<li>Next: 服务执行完成后下一个执行的&quot;状态&quot;</li>
<li>Choices: Choice类型的&quot;状态&quot;里, 可选的分支列表, 分支中的Expression为SpringEL表达式, Next为当表达式成立时执行的下一个&quot;状态&quot;</li>
<li>ErrorCode: Fail类型&quot;状态&quot;的错误码</li>
<li>Message: Fail类型&quot;状态&quot;的错误信息</li>
</ul>
<p>更多详细的状态语言解释请看<a href="#State-language-referance">State language referance</a>章节</p>
<p>更多详细的状态语言使用示例见<a href="https://github.com/seata/seata/tree/develop/test/src/test/java/io/seata/saga/engine">https://github.com/seata/seata/tree/develop/test/src/test/java/io/seata/saga/engine</a></p>
<h3>Demo 运行指南</h3>
<h4>step 1 启动 SEATA Server</h4>
<p>运行 <a href="https://github.com/seata/seata-samples/blob/master/saga/sofarpc-saga-sample/src/test/java/io/seata/samples/saga/SeataServerStarter.java">SeataServerStarter</a> ，启动 Seata Server；</p>
<h4>step 2 启动 dubbo provider Demo</h4>
<p>运行 <a href="https://github.com/seata/seata-samples/blob/master/saga/dubbo-saga-sample/src/test/java/io/seata/samples/saga/starter/DubboSagaProviderStarter.java">DubboSagaProviderStarter</a> ，启动 dubbo provider；</p>
<h4>step 3 启动 Saga Demo</h4>
<p>运行 <a href="https://github.com/seata/seata-samples/blob/master/saga/dubbo-saga-sample/src/main/java/io/seata/samples/saga/starter/DubboSagaTransactionStarter.java">DubboSagaTransactionStarter</a> , 启动 demo工程；</p>
<blockquote>
<p>Demo中的数据库使用的是H2内存数据库, 生产上建议使用与业务相同的库, 目前支持Oracle, Mysql, DB2. 建表语句在 <a href="https://github.com/seata/seata/tree/develop/saga/seata-saga-engine-store/src/main/resources/sql">https://github.com/seata/seata/tree/develop/saga/seata-saga-engine-store/src/main/resources/sql</a></p>
</blockquote>
<blockquote>
<p>Demo中还有调用本地服务和调用SOFA RPC服务的示例</p>
</blockquote>
<h2>状态机设计器</h2>
<p>Seata Saga 提供了一个可视化的状态机设计器方便用户使用，代码和运行指南请参考：
<a href="https://github.com/seata/seata/tree/develop/saga/seata-saga-statemachine-designer">https://github.com/seata/seata/tree/develop/saga/seata-saga-statemachine-designer</a></p>
<p>状态机设计器截图:
<img src="/img/saga/seata-saga-statemachine-designer.png?raw=true" alt="状态机设计器"></p>
<p>状态机设计器演示地址:<a href="/saga_designer/index.html">http://seata.io/saga_designer/index.html</a></p>
<p>状态机设计器视频教程:<a href="/saga_designer/vedio.html">http://seata.io/saga_designer/vedio.html</a></p>
<h2>最佳实践</h2>
<h3>Saga 服务设计的实践经验</h3>
<h4>允许空补偿</h4>
<ul>
<li>空补偿：原服务未执行，补偿服务执行了</li>
<li>出现原因：
<ul>
<li>原服务 超时（丢包）</li>
<li>Saga 事务触发 回滚</li>
<li>未收到 原服务请求，先收到 补偿请求</li>
</ul>
</li>
</ul>
<p>所以服务设计时需要允许空补偿, 即没有找到要补偿的业务主键时返回补偿成功并将原业务主键记录下来</p>
<h4>防悬挂控制</h4>
<ul>
<li>悬挂：补偿服务 比 原服务 先执行</li>
<li>出现原因：
<ul>
<li>原服务 超时（拥堵）</li>
<li>Saga 事务回滚，触发 回滚</li>
<li>拥堵的 原服务 到达</li>
</ul>
</li>
</ul>
<p>所以要检查当前业务主键是否已经在空补偿记录下来的业务主键中存在，如果存在则要拒绝服务的执行</p>
<h4>幂等控制</h4>
<ul>
<li>原服务与补偿服务都需要保证幂等性, 由于网络可能超时, 可以设置重试策略，重试发生时要通过幂等控制避免业务数据重复更新</li>
</ul>
<h3>缺乏隔离性的应对</h3>
<ul>
<li>由于 Saga 事务不保证隔离性, 在极端情况下可能由于脏写无法完成回滚操作, 比如举一个极端的例子, 分布式事务内先给用户A充值, 然后给用户B扣减余额, 如果在给A用户充值成功, 在事务提交以前, A用户把余额消费掉了, 如果事务发生回滚, 这时则没有办法进行补偿了。这就是缺乏隔离性造成的典型的问题, 实践中一般的应对方法是：
<ul>
<li>业务流程设计时遵循“宁可长款, 不可短款”的原则, 长款意思是客户少了钱机构多了钱, 以机构信誉可以给客户退款, 反之则是短款, 少的钱可能追不回来了。所以在业务流程设计上一定是先扣款。</li>
<li>有些业务场景可以允许让业务最终成功, 在回滚不了的情况下可以继续重试完成后面的流程, 所以状态机引擎除了提供“回滚”能力还需要提供“向前”恢复上下文继续执行的能力, 让业务最终执行成功, 达到最终一致性的目的。</li>
</ul>
</li>
</ul>
<h3>性能优化</h3>
<ul>
<li>配置客户端参数<code>client.rm.report.success.enable=false</code>，可以在当分支事务执行成功时不上报分支状态到server，从而提升性能。</li>
</ul>
<blockquote>
<p>当上一个分支事务的状态还没有上报的时候，下一个分支事务已注册，可以认为上一个实际已成功</p>
</blockquote>
<h2>API referance</h2>
<h4>StateMachineEngine API</h4>
<pre><code class="language-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">StateMachineEngine</span> </span>{

    <span class="hljs-comment">/**
     * start a state machine instance
     * <span class="hljs-doctag">@param</span> stateMachineName
     * <span class="hljs-doctag">@param</span> tenantId
     * <span class="hljs-doctag">@param</span> startParams
     * <span class="hljs-doctag">@return</span>
     * <span class="hljs-doctag">@throws</span> EngineExecutionException
     */</span>
    <span class="hljs-function">StateMachineInstance <span class="hljs-title">start</span><span class="hljs-params">(String stateMachineName, String tenantId, Map&lt;String, Object&gt; startParams)</span> <span class="hljs-keyword">throws</span> EngineExecutionException</span>;

    <span class="hljs-comment">/**
     * start a state machine instance with businessKey
     * <span class="hljs-doctag">@param</span> stateMachineName
     * <span class="hljs-doctag">@param</span> tenantId
     * <span class="hljs-doctag">@param</span> businessKey
     * <span class="hljs-doctag">@param</span> startParams
     * <span class="hljs-doctag">@return</span>
     * <span class="hljs-doctag">@throws</span> EngineExecutionException
     */</span>
    <span class="hljs-function">StateMachineInstance <span class="hljs-title">startWithBusinessKey</span><span class="hljs-params">(String stateMachineName, String tenantId, String businessKey, Map&lt;String, Object&gt; startParams)</span> <span class="hljs-keyword">throws</span> EngineExecutionException</span>;

    <span class="hljs-comment">/**
     * start a state machine instance asynchronously
     * <span class="hljs-doctag">@param</span> stateMachineName
     * <span class="hljs-doctag">@param</span> tenantId
     * <span class="hljs-doctag">@param</span> startParams
     * <span class="hljs-doctag">@param</span> callback
     * <span class="hljs-doctag">@return</span>
     * <span class="hljs-doctag">@throws</span> EngineExecutionException
     */</span>
    <span class="hljs-function">StateMachineInstance <span class="hljs-title">startAsync</span><span class="hljs-params">(String stateMachineName, String tenantId, Map&lt;String, Object&gt; startParams, AsyncCallback callback)</span> <span class="hljs-keyword">throws</span> EngineExecutionException</span>;

    <span class="hljs-comment">/**
     * start a state machine instance asynchronously with businessKey
     * <span class="hljs-doctag">@param</span> stateMachineName
     * <span class="hljs-doctag">@param</span> tenantId
     * <span class="hljs-doctag">@param</span> businessKey
     * <span class="hljs-doctag">@param</span> startParams
     * <span class="hljs-doctag">@param</span> callback
     * <span class="hljs-doctag">@return</span>
     * <span class="hljs-doctag">@throws</span> EngineExecutionException
     */</span>
    <span class="hljs-function">StateMachineInstance <span class="hljs-title">startWithBusinessKeyAsync</span><span class="hljs-params">(String stateMachineName, String tenantId, String businessKey, Map&lt;String, Object&gt; startParams, AsyncCallback callback)</span> <span class="hljs-keyword">throws</span> EngineExecutionException</span>;

    <span class="hljs-comment">/**
     * forward restart a failed state machine instance
     * <span class="hljs-doctag">@param</span> stateMachineInstId
     * <span class="hljs-doctag">@param</span> replaceParams
     * <span class="hljs-doctag">@return</span>
     * <span class="hljs-doctag">@throws</span> ForwardInvalidException
     */</span>
    <span class="hljs-function">StateMachineInstance <span class="hljs-title">forward</span><span class="hljs-params">(String stateMachineInstId, Map&lt;String, Object&gt; replaceParams)</span> <span class="hljs-keyword">throws</span> ForwardInvalidException</span>;

    <span class="hljs-comment">/**
     * forward restart a failed state machine instance asynchronously
     * <span class="hljs-doctag">@param</span> stateMachineInstId
     * <span class="hljs-doctag">@param</span> replaceParams
     * <span class="hljs-doctag">@param</span> callback
     * <span class="hljs-doctag">@return</span>
     * <span class="hljs-doctag">@throws</span> ForwardInvalidException
     */</span>
    <span class="hljs-function">StateMachineInstance <span class="hljs-title">forwardAsync</span><span class="hljs-params">(String stateMachineInstId, Map&lt;String, Object&gt; replaceParams, AsyncCallback callback)</span> <span class="hljs-keyword">throws</span> ForwardInvalidException</span>;

    <span class="hljs-comment">/**
     * compensate a state machine instance
     * <span class="hljs-doctag">@param</span> stateMachineInstId
     * <span class="hljs-doctag">@param</span> replaceParams
     * <span class="hljs-doctag">@return</span>
     * <span class="hljs-doctag">@throws</span> EngineExecutionException
     */</span>
    <span class="hljs-function">StateMachineInstance <span class="hljs-title">compensate</span><span class="hljs-params">(String stateMachineInstId, Map&lt;String, Object&gt; replaceParams)</span> <span class="hljs-keyword">throws</span> EngineExecutionException</span>;

    <span class="hljs-comment">/**
     * compensate a state machine instance asynchronously
     * <span class="hljs-doctag">@param</span> stateMachineInstId
     * <span class="hljs-doctag">@param</span> replaceParams
     * <span class="hljs-doctag">@param</span> callback
     * <span class="hljs-doctag">@return</span>
     * <span class="hljs-doctag">@throws</span> EngineExecutionException
     */</span>
    <span class="hljs-function">StateMachineInstance <span class="hljs-title">compensateAsync</span><span class="hljs-params">(String stateMachineInstId, Map&lt;String, Object&gt; replaceParams, AsyncCallback callback)</span> <span class="hljs-keyword">throws</span> EngineExecutionException</span>;

    <span class="hljs-comment">/**
     * skip current failed state instance and forward restart state machine instance
     * <span class="hljs-doctag">@param</span> stateMachineInstId
     * <span class="hljs-doctag">@return</span>
     * <span class="hljs-doctag">@throws</span> EngineExecutionException
     */</span>
    <span class="hljs-function">StateMachineInstance <span class="hljs-title">skipAndForward</span><span class="hljs-params">(String stateMachineInstId)</span> <span class="hljs-keyword">throws</span> EngineExecutionException</span>;

    <span class="hljs-comment">/**
     * skip current failed state instance and forward restart state machine instance asynchronously
     * <span class="hljs-doctag">@param</span> stateMachineInstId
     * <span class="hljs-doctag">@param</span> callback
     * <span class="hljs-doctag">@return</span>
     * <span class="hljs-doctag">@throws</span> EngineExecutionException
     */</span>
    <span class="hljs-function">StateMachineInstance <span class="hljs-title">skipAndForwardAsync</span><span class="hljs-params">(String stateMachineInstId, AsyncCallback callback)</span> <span class="hljs-keyword">throws</span> EngineExecutionException</span>;

    <span class="hljs-comment">/**
     * get state machine configurations
     * <span class="hljs-doctag">@return</span>
     */</span>
    <span class="hljs-function">StateMachineConfig <span class="hljs-title">getStateMachineConfig</span><span class="hljs-params">()</span></span>;
}
</code></pre>
<h4>StateMachine Execution Instance API:</h4>
<pre><code class="language-java">StateLogRepository stateLogRepository = stateMachineEngine.getStateMachineConfig().getStateLogRepository();
StateMachineInstance stateMachineInstance = stateLogRepository.getStateMachineInstanceByBusinessKey(businessKey, tenantId);

<span class="hljs-comment">/**
 * State Log Repository
 *
 * <span class="hljs-doctag">@author</span> lorne.cl
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">StateLogRepository</span> </span>{

    <span class="hljs-comment">/**
     * Get state machine instance
     *
     * <span class="hljs-doctag">@param</span> stateMachineInstanceId
     * <span class="hljs-doctag">@return</span>
     */</span>
    <span class="hljs-function">StateMachineInstance <span class="hljs-title">getStateMachineInstance</span><span class="hljs-params">(String stateMachineInstanceId)</span></span>;

    <span class="hljs-comment">/**
     * Get state machine instance by businessKey
     *
     * <span class="hljs-doctag">@param</span> businessKey
     * <span class="hljs-doctag">@param</span> tenantId
     * <span class="hljs-doctag">@return</span>
     */</span>
    <span class="hljs-function">StateMachineInstance <span class="hljs-title">getStateMachineInstanceByBusinessKey</span><span class="hljs-params">(String businessKey, String tenantId)</span></span>;

    <span class="hljs-comment">/**
     * Query the list of state machine instances by parent id
     *
     * <span class="hljs-doctag">@param</span> parentId
     * <span class="hljs-doctag">@return</span>
     */</span>
    <span class="hljs-function">List&lt;StateMachineInstance&gt; <span class="hljs-title">queryStateMachineInstanceByParentId</span><span class="hljs-params">(String parentId)</span></span>;

    <span class="hljs-comment">/**
     * Get state instance
     *
     * <span class="hljs-doctag">@param</span> stateInstanceId
     * <span class="hljs-doctag">@param</span> machineInstId
     * <span class="hljs-doctag">@return</span>
     */</span>
    <span class="hljs-function">StateInstance <span class="hljs-title">getStateInstance</span><span class="hljs-params">(String stateInstanceId, String machineInstId)</span></span>;

    <span class="hljs-comment">/**
     * Get a list of state instances by state machine instance id
     *
     * <span class="hljs-doctag">@param</span> stateMachineInstanceId
     * <span class="hljs-doctag">@return</span>
     */</span>
    <span class="hljs-function">List&lt;StateInstance&gt; <span class="hljs-title">queryStateInstanceListByMachineInstanceId</span><span class="hljs-params">(String stateMachineInstanceId)</span></span>;
}
</code></pre>
<h4>StateMachine Definition API:</h4>
<pre><code class="language-java">StateMachineRepository stateMachineRepository = stateMachineEngine.getStateMachineConfig().getStateMachineRepository();
StateMachine stateMachine = stateMachineRepository.getStateMachine(stateMachineName, tenantId);

<span class="hljs-comment">/**
 * StateMachineRepository
 *
 * <span class="hljs-doctag">@author</span> lorne.cl
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">StateMachineRepository</span> </span>{

    <span class="hljs-comment">/**
     * Gets get state machine by id.
     *
     * <span class="hljs-doctag">@param</span> stateMachineId the state machine id
     * <span class="hljs-doctag">@return</span> the get state machine by id
     */</span>
    <span class="hljs-function">StateMachine <span class="hljs-title">getStateMachineById</span><span class="hljs-params">(String stateMachineId)</span></span>;

    <span class="hljs-comment">/**
     * Gets get state machine.
     *
     * <span class="hljs-doctag">@param</span> stateMachineName the state machine name
     * <span class="hljs-doctag">@param</span> tenantId         the tenant id
     * <span class="hljs-doctag">@return</span> the get state machine
     */</span>
    <span class="hljs-function">StateMachine <span class="hljs-title">getStateMachine</span><span class="hljs-params">(String stateMachineName, String tenantId)</span></span>;

    <span class="hljs-comment">/**
     * Gets get state machine.
     *
     * <span class="hljs-doctag">@param</span> stateMachineName the state machine name
     * <span class="hljs-doctag">@param</span> tenantId         the tenant id
     * <span class="hljs-doctag">@param</span> version          the version
     * <span class="hljs-doctag">@return</span> the get state machine
     */</span>
    <span class="hljs-function">StateMachine <span class="hljs-title">getStateMachine</span><span class="hljs-params">(String stateMachineName, String tenantId, String version)</span></span>;

    <span class="hljs-comment">/**
     * Register the state machine to the repository (if the same version already exists, return the existing version)
     *
     * <span class="hljs-doctag">@param</span> stateMachine
     */</span>
    <span class="hljs-function">StateMachine <span class="hljs-title">registryStateMachine</span><span class="hljs-params">(StateMachine stateMachine)</span></span>;

    <span class="hljs-comment">/**
     * registry by resources
     *
     * <span class="hljs-doctag">@param</span> resources
     * <span class="hljs-doctag">@param</span> tenantId
     */</span>
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">registryByResources</span><span class="hljs-params">(Resource[] resources, String tenantId)</span> <span class="hljs-keyword">throws</span> IOException</span>;
}
</code></pre>
<h2>Config referance</h2>
<h4>在Spring Bean配置文件中配置一个StateMachineEngine</h4>
<pre><code class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"dataSource"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"..."</span>&gt;</span>
...
<span class="hljs-tag">&lt;<span class="hljs-name">bean</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"stateMachineEngine"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"io.seata.saga.engine.impl.ProcessCtrlStateMachineEngine"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"stateMachineConfig"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">"dbStateMachineConfig"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">property</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"dbStateMachineConfig"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"io.seata.saga.engine.config.DbStateMachineConfig"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"dataSource"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">"dataSource"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">property</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"resources"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"statelang/*.json"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">property</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"enableAsync"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"true"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">property</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"threadPoolExecutor"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">"threadExecutor"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">property</span>&gt;</span><span class="hljs-comment">&lt;!-- 事件驱动执行时使用的线程池, 如果所有状态机都同步执行可以不需要 --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"applicationId"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"saga_sample"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">property</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"txServiceGroup"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"my_test_tx_group"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">property</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"threadExecutor"</span>
        <span class="hljs-attr">class</span>=<span class="hljs-string">"org.springframework.scheduling.concurrent.ThreadPoolExecutorFactoryBean"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"threadNamePrefix"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"SAGA_ASYNC_EXE_"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"corePoolSize"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"1"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"maxPoolSize"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"20"</span> /&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span>

<span class="hljs-comment">&lt;!-- Seata Server进行事务恢复时需要通过这个Holder拿到stateMachineEngine实例 --&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">bean</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"io.seata.saga.rm.StateMachineEngineHolder"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"stateMachineEngine"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">"stateMachineEngine"</span>/&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">bean</span>&gt;</span>
</code></pre>
<h2>State language referance</h2>
<h3>&quot;状态机&quot;的属性列表</h3>
<pre><code class="language-json">{
    <span class="hljs-attr">"Name"</span>: <span class="hljs-string">"reduceInventoryAndBalance"</span>,
    <span class="hljs-attr">"Comment"</span>: <span class="hljs-string">"reduce inventory then reduce balance in a transaction"</span>,
    <span class="hljs-attr">"StartState"</span>: <span class="hljs-string">"ReduceInventory"</span>,
    <span class="hljs-attr">"Version"</span>: <span class="hljs-string">"0.0.1"</span>,
    <span class="hljs-attr">"States"</span>: {
    }
}
</code></pre>
<ul>
<li>Name: 表示状态机的名称，必须唯一</li>
<li>Comment: 状态机的描述</li>
<li>Version: 状态机定义版本</li>
<li>StartState: 启动时运行的第一个&quot;状态&quot;</li>
<li>States: 状态列表，是一个map结构，key是&quot;状态&quot;的名称，在状态机内必须唯一, value是一个map结构表示&quot;状态&quot;的属性列表</li>
</ul>
<h3>各种&quot;状态&quot;的属性列表</h3>
<h4>ServiceTask:</h4>
<pre><code class="language-json">"States": {
    ...
    "ReduceBalance": {
        "Type": "ServiceTask",
        "ServiceName": "balanceAction",
        "ServiceMethod": "reduce",
        "CompensateState": "CompensateReduceBalance",
        "IsForUpdate": true,
        "IsPersist": true,
        "IsAsync": false,
        "Input": [
            "$.[businessKey]",
            "$.[amount]",
            {
                "throwException" : "$.[mockReduceBalanceFail]"
            }
        ],
        "Output": {
            "compensateReduceBalanceResult": "$.#root"
        },
        "Status": {
            "#root == true": "SU",
            "#root == false": "FA",
            "$Exception{java.lang.Throwable}": "UN"
        },
        "Retry": [
            {
                "Exceptions": ["io.seata.saga.engine.mock.DemoException"],
                "IntervalSeconds": 1.5,
                "MaxAttempts": 3,
                "BackoffRate": 1.5
            },
            {
                "IntervalSeconds": 1,
                "MaxAttempts": 3,
                "BackoffRate": 1.5
            }
        ],
        "Catch": [
            {
                "Exceptions": [
                    "java.lang.Throwable"
                ],
                "Next": "CompensationTrigger"
            }
        ],
        "Next": "Succeed"
    }
    ...
}
</code></pre>
<ul>
<li>ServiceName: 服务名称，通常是服务的beanId</li>
<li>ServiceMethod: 服务方法名称</li>
<li>CompensateState: 该&quot;状态&quot;的补偿&quot;状态&quot;</li>
<li>IsForUpdate: 标识该服务会更新数据, 默认是false, 如果配置了CompensateState则默认是true, 有补偿服务的服务肯定是数据更新类服务</li>
<li>IsPersist: 执行日志是否进行存储, 默认是true, 有一些查询类的服务可以配置为false, 执行日志不进行存储提高性能, 因为当异常恢复时可以重复执行</li>
<li>IsAsync: 异步调用服务, 注意: 因为异步调用服务会忽略服务的返回结果, 所以用户定义的服务执行状态映射(下面的Status属性)将被忽略, 默认为服务调用成功, 如果提交异步调用就失败(比如线程池已满)则为服务执行状态为失败</li>
<li>Input: 调用服务的输入参数列表, 是一个数组, 对应于服务方法的参数列表, $.表示使用表达式从状态机上下文中取参数，表达使用的<a href="https://docs.spring.io/spring/docs/4.3.10.RELEASE/spring-framework-reference/html/expressions.html">SpringEL</a>, 如果是常量直接写值即可。复杂的参数如何传入见:<a href="#%E5%A4%8D%E6%9D%82%E5%8F%82%E6%95%B0%E7%9A%84Input%E5%AE%9A%E4%B9%89">复杂参数的Input定义</a></li>
<li>Output: 将服务返回的参数赋值到状态机上下文中, 是一个map结构，key为放入到状态机上文时的key（状态机上下文也是一个map），value中$.是表示SpringEL表达式，表示从服务的返回参数中取值，#root表示服务的整个返回参数</li>
<li>Status: 服务执行状态映射，框架定义了三个状态，SU 成功、FA 失败、UN 未知, 我们需要把服务执行的状态映射成这三个状态，帮助框架判断整个事务的一致性，是一个map结构，key是条件表达式，一般是取服务的返回值或抛出的异常进行判断，默认是SpringEL表达式判断服务返回参数，带$Exception{开头表示判断异常类型。value是当这个条件表达式成立时则将服务执行状态映射成这个值</li>
<li>Catch: 捕获到异常后的路由</li>
<li>Retry: 捕获异常后的重试策略, 是个数组可以配置多个规则, <code>Exceptions</code> 为匹配的的异常列表, <code>IntervalSeconds</code> 为重试间隔, <code>MaxAttempts</code> 为最大重试次数, <code>BackoffRate</code> 下一次重试间隔相对于上一次重试间隔的倍数，比如说上次一重试间隔是2秒, <code>BackoffRate=1.5</code> 则下一次重试间隔是3秒。<code>Exceptions</code> 属性可以不配置, 不配置时表示框架自动匹配网络超时异常。当在重试过程中发生了别的异常，框架会重新匹配规则，并按新规则进行重试，同一种规则的总重试次数不会超过该规则的<code>MaxAttempts</code></li>
<li>Next: 服务执行完成后下一个执行的&quot;状态&quot;</li>
</ul>
<blockquote>
<p>当没有配置Status对服务执行状态进行映射, 系统会自动判断状态:</p>
<ul>
<li>没有异常则认为执行成功,</li>
<li>如果有异常, 则判断异常是不是网路连接超时, 如果是则认为是FA</li>
<li>如果是其它异常, 服务IsForUpdate=true则状态为UN, 否则为FA</li>
</ul>
</blockquote>
<blockquote>
<p>整个状态机的执行状态如何判断？是由框架自己判断的, 状态机有两个状态: status(正向执行状态), compensateStatus(补偿状态)：</p>
<ul>
<li>如果所有服务执行成功（事务提交成功）则status=SU, compensateStatus=null</li>
<li>如果有服务执行失败且存在更新类服务执行成功且没有进行补偿（事务提交失败） 则status=UN, compensateStatus=null</li>
<li>如果有服务执行失败且不存在更新类服务执行成功且没有进行补偿（事务提交失败） 则status=FA, compensateStatus=null</li>
<li>如果补偿成功（事务回滚成功）则status=FA/UN, compensateStatus=SU</li>
<li>发生补偿且有未补偿成功的服务（回滚失败）则status=FA/UN, compensateStatus=UN</li>
<li>存在事务提交或回滚失败的情况Seata Sever都会不断发起重试</li>
</ul>
</blockquote>
<h4>Choice:</h4>
<pre><code class="language-json">"ChoiceState":{
    "Type": "Choice",
    "Choices":[
        {
            "Expression":"[reduceInventoryResult] == true",
            "Next":"ReduceBalance"
        }
    ],
    "Default":"Fail"
}
</code></pre>
<p>Choice类型的&quot;状态&quot;是单项选择路由
Choices: 可选的分支列表, 只会选择第一个条件成立的分支
Expression: SpringEL表达式
Next: 当Expression表达式成立时执行的下一个&quot;状态&quot;</p>
<h4>Succeed:</h4>
<pre><code class="language-json">"Succeed": {
    "Type":"Succeed"
}
</code></pre>
<p>运行到&quot;Succeed状态&quot;表示状态机正常结束, 正常结束不代表成功结束, 是否成功要看每个&quot;状态&quot;是否都成功</p>
<h4>Fail:</h4>
<pre><code class="language-json">"Fail": {
    "Type":"Fail",
    "ErrorCode": "PURCHASE_FAILED",
    "Message": "purchase failed"
}
</code></pre>
<p>运行到&quot;Fail状态&quot;状态机异常结束, 异常结束时可以配置ErrorCode和Message, 表示错误码和错误信息, 可以用于给调用方返回错误码和消息</p>
<h4>CompensationTrigger:</h4>
<pre><code class="language-json">"CompensationTrigger": {
    "Type": "CompensationTrigger",
    "Next": "Fail"
}
</code></pre>
<p>CompensationTrigger类型的state是用于触发补偿事件, 回滚分布式事务
Next: 补偿成功后路由到的state</p>
<h4>SubStateMachine:</h4>
<pre><code class="language-json">"CallSubStateMachine": {
    "Type": "SubStateMachine",
    "StateMachineName": "simpleCompensationStateMachine",
    "CompensateState": "CompensateSubMachine",
    "Input": [
        {
            "a": "$.1",
            "barThrowException": "$.[barThrowException]",
            "fooThrowException": "$.[fooThrowException]",
            "compensateFooThrowException": "$.[compensateFooThrowException]"
        }
    ],
    "Output": {
        "fooResult": "$.#root"
    },
    "Next": "Succeed"
}
</code></pre>
<p>SubStateMachine类型的&quot;状态&quot;是调用子状态机
StateMachineName: 要调用的子状态机名称
CompensateState: 子状态机的补偿state, 可以不配置, 系统会自动创建它的补偿state, 子状态机的补偿实际就是调用子状态机的compensate方法, 所以用户并不需要自己实现一个对子状态机的补偿服务。当配置这个属性时, 可以里利用Input属性自定义传入一些变量, 见下面的CompensateSubMachine</p>
<h4>CompensateSubMachine:</h4>
<pre><code class="language-json">"CompensateSubMachine": {
    "Type": "CompensateSubMachine",
    "Input": [
        {
            "compensateFooThrowException": "$.[compensateFooThrowException]"
        }
    ]
}
</code></pre>
<p>CompensateSubMachine类型的state是专门用于补偿一个子状态机的state，它会调用子状态机的compensate方法，可以利用Input属性传入一些自定义的变量, Status属性自定判断补偿是否成功</p>
<h4>复杂参数的Input定义</h4>
<pre><code class="language-json">"FirstState": {
    "Type": "ServiceTask",
    "ServiceName": "demoService",
    "ServiceMethod": "complexParameterMethod",
    "Next": "ChoiceState",
    "ParameterTypes" : ["java.lang.String", "int", "io.seata.saga.engine.mock.DemoService$People", "[Lio.seata.saga.engine.mock.DemoService$People;", "java.util.List", "java.util.Map"],
    "Input": [
        "$.[people].name",
        "$.[people].age",
        {
            "name": "$.[people].name",
            "age": "$.[people].age",
            "childrenArray": [
                {
                    "name": "$.[people].name",
                    "age": "$.[people].age"
                },
                {
                    "name": "$.[people].name",
                    "age": "$.[people].age"
                }
            ],
            "childrenList": [
                {
                    "name": "$.[people].name",
                    "age": "$.[people].age"
                },
                {
                    "name": "$.[people].name",
                    "age": "$.[people].age"
                }
            ],
            "childrenMap": {
                "lilei": {
                    "name": "$.[people].name",
                    "age": "$.[people].age"
                }
            }
        },
        [
            {
                "name": "$.[people].name",
                "age": "$.[people].age"
            },
            {
                "name": "$.[people].name",
                "age": "$.[people].age"
            }
        ],
        [
            {
                "@type": "io.seata.saga.engine.mock.DemoService$People",
                "name": "$.[people].name",
                "age": "$.[people].age"
            }
        ],
        {
            "lilei": {
                "@type": "io.seata.saga.engine.mock.DemoService$People",
                "name": "$.[people].name",
                "age": "$.[people].age"
            }
        }
    ],
    "Output": {
        "complexParameterMethodResult": "$.#root"
    }
}
</code></pre>
<p>上面的complexParameterMethod方法定义如下:</p>
<pre><code class="language-java"><span class="hljs-function">People <span class="hljs-title">complexParameterMethod</span><span class="hljs-params">(String name, <span class="hljs-keyword">int</span> age, People people, People[] peopleArrya, List&lt;People&gt; peopleList, Map&lt;String, People&gt; peopleMap)</span>

class People </span>{

    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span>    age;

    <span class="hljs-keyword">private</span> People[] childrenArray;
    <span class="hljs-keyword">private</span> List&lt;People&gt; childrenList;
    <span class="hljs-keyword">private</span> Map&lt;String, People&gt; childrenMap;

    ...
}
</code></pre>
<p>启动状态机时传入参数:</p>
<pre><code class="language-java">Map&lt;String, Object&gt; paramMap = <span class="hljs-keyword">new</span> HashMap&lt;&gt;(<span class="hljs-number">1</span>);
People people = <span class="hljs-keyword">new</span> People();
people.setName(<span class="hljs-string">"lilei"</span>);
people.setAge(<span class="hljs-number">18</span>);
paramMap.put(<span class="hljs-string">"people"</span>, people);
String stateMachineName = <span class="hljs-string">"simpleStateMachineWithComplexParams"</span>;
StateMachineInstance inst = stateMachineEngine.start(stateMachineName, <span class="hljs-keyword">null</span>, paramMap);
</code></pre>
<blockquote>
<p>注意ParameterTypes属性是可以不用传的，调用的方法的参数列表中有Map, List这种可以带泛型的集合类型, 因为java编译会丢失泛型, 所以需要用这个属性, 同时在Input的json中对应的对这个json加&quot;@type&quot;来申明泛型(集合的元素类型)</p>
</blockquote>
<h2>FAQ</h2>
<hr>
<p><strong>问:</strong> saga服务流程可以不配置吗，使用全局事务id串起来，这样省去配置的工作量，再加上人工配置难免会配置错误？</p>
<p><strong>答:</strong> saga一般有两种实现，一种是基于状态机定义，比如apache camel saga、eventuate，一种是基于注解+拦截器实现，比如serviceComb saga，后者是不需要配置状态图的。由于 Saga 事务不保证隔离性, 在极端情况下可能由于脏写无法完成回滚操作, 比如举一个极端的例子, 分布式事务内先给用户A充值, 然后给用户B扣减余额, 如果在给A用户充值成功, 在事务提交以前, A用户把余额消费掉了, 如果事务发生回滚, 这时则没有办法进行补偿了，有些业务场景可以允许让业务最终成功, 在回滚不了的情况下可以继续重试完成后面的流程, 基于状态机引擎除可以提供“回滚”能力外, 还可以提供“向前”恢复上下文继续执行的能力, 让业务最终执行成功, 达到最终一致性的目的，所以在实际生产中基于状态机的实现应用更多。后续也会提供基于注解+拦截器实现。</p>
<hr>
<p><strong>问:</strong> 比如有 服务A在系统1里面，服务B在系统2里面。全局事务由A开启，流程调用B开启子事务，那系统2也需要维护Saga状态机的三个表吗，也需要在Spring Bean配置文件中配置一个StateMachineEngine吗?</p>
<p><strong>答:</strong> 不需要, 只在发起方记录日志. 由于只在发起方记录日志同时对参与者服务没有接口参数的要求，使得Saga可以方便集成其它机构或遗留系统的服务</p>
<hr>
<p><strong>问:</strong> 如果 系统1和系统2里面的服务，可以相互调用。系统12都可以开启全局事务，可以这样使用吗。那1和2 都需要维护Saga状态机的三个表，也需要在Spring Bean配置文件中配置一个StateMachineEngine？</p>
<p><strong>答:</strong> 可以这样使用，如果两个系统都开启saga事务，那就要记录那三个表配置StateMachineEngine</p>
<hr>
<p><strong>问:</strong> 使用 Seata 的时候，现在是 AT 模式 如果改成 saga 模式的话，改造会大吗？</p>
<p><strong>答:</strong> AT 模式完全是透明的，Saga 是有侵入性的，要配置状态机 json，如果服务多改造会比较大</p>
<hr>
<p><strong>问:</strong> Saga 模式是不是基于 AT 来加强的长事务处理呢？</p>
<p><strong>答:</strong> 没有基于 AT，客户端完全是两套，Server 端是复用的。你也可以看 Saga 的单元测试，那里有很多示例：<a href="https://github.com/seata/seata/tree/develop/test/src/test/java/io/seata/saga/engine">https://github.com/seata/seata/tree/develop/test/src/test/java/io/seata/saga/engine</a></p>
<hr>
<p><strong>问:</strong> 开发者文档中状态机引擎原理图里的EventQueue只是开启分布式事务的系统来进行事件驱动，调用其它系统服务像调用本地一样。系统之间还是RPC调用是吧。而不是系统之前也是纯事件驱动的？（&quot;系统之间也是纯事件驱动的&quot; 指 RPC 也是非阻塞的）</p>
<p><strong>答:</strong> 节点与节点间是事件驱动的, RPC 的非阻塞需要 rpc client 支持，理论上也是可以的。rpc client 如果也是非阻塞 IO，那么所有环节都是异步了。</p>
<hr>
<p><strong>问:</strong> 考虑一个业务流程， 它后续的子流程， 不管谁先运行都不会相互影响，可以异步调用。子流程是其它系统服务。Seata Saga 是不是实现了这点，其实我没看明白 ，Seata Saga异步调用具体是不是各个节点异步了？</p>
<p><strong>答:</strong> Saga的异步启动一个状态机(stateMachineEngine.startAsync)是指状态机内所有的状态都是事件驱动来执行的, 整个流程实际是同步的, 上一个状态结束才产生下一个状态的事件. 而异步调用一个服务是配置该ServiceTask为&quot;IsAsync&quot;:true, 这个服务将会异步调用, 不会阻塞状态机的推进, 状态机不关心它的执行结果.</p>
<hr>
<p><strong>问:</strong> Saga源码中事件驱动层同步bus和异步bus是什么作用？</p>
<p><strong>答:</strong> 同步BUS是线程阻塞的，等整个状态机执行完毕才返回，异步BUS是非线程阻塞的，调用后立即返回，状态机执行完毕后回调你的Callback。</p>
<hr>
<p><strong>问:</strong> IsPersist: 执行日志是否进行存储，默认是true，有一些查询类的服务可以配置在false，执行日志不进行存储提高性能，因为当异常恢复时可以重复执行？</p>
<p><strong>答:</strong> 是的可以配置成false, 不过建议先保持默认，这样在查询执行日志比较全，真的要做性能调优再配，一般不会有性能问题</p>
<hr>
<p><strong>问:</strong>  seata saga  开启事务的客户端或者seata server服务端宕机或者重启，未完成的状态机实例是怎么保证继续执行下去的?谁去触发这个操作?</p>
<p><strong>答:</strong> 状态机实例在本地数据库有记录日志，通过日志恢复。seata server 会触触发事务恢复。</p>
<hr>
<p><strong>问:</strong> saga 的json文件  支持热部署吗?</p>
<p><strong>答:</strong> 支持, stateMachineEngine.getStateMachineConfig().getStateMachineRepository().registryByResources()。不过java代码和服务需要自己实现支持热部署</p>
<hr>
<p><strong>问:</strong> 出参入参都放在saga的上下文中，如果参数内容较多较大，业务量又大的话，对内存有限制吗?</p>
<p><strong>答:</strong> 没有做限制，建议无关的参数不要放到上下文。下一个服务需要用的参数、或用于分支判断的参数可以放入上下文。</p>
<hr>
<p><strong>问:</strong> 确认个事情：每个节点，要么自己方法内部 Catch 异常处理，使最终有返回信息。要么自己内部可以不处理，交由状态机引擎捕获异常，在 json 中定义 Catch 属性。 而不是补偿节点能够自动触发补偿，需要补偿必须手动在 json，由 Catch 或者 Choices 属性路由到 CompensationTrigger？</p>
<p><strong>答:</strong> 对的，这个是为了提高灵活性。用户可以自己控制是否进行回滚，因为并不是所有异常都要回滚，可能有一些自定义处理手段。</p>
<hr>
<p><strong>问:</strong> 所以 Catch 和 Choices 可以随便路由到想要的 state  对吧？</p>
<p><strong>答:</strong> 是的。这种自定义出发补偿的设计是参考了 bpmn2.0 的。</p>
<hr>
<p><strong>问:</strong> 还有关于 json 文件，我打算一条流程，就定义一个 json，虽然有的流程很像，用 Choices，可以解决。但是感觉 json 还是要尽量简单。这样考虑对吗？</p>
<p><strong>答:</strong> 你可以考虑用子状态机来复用，子状态机会多生成一行 stateMachineInstance 记录，但对性能影响应该不大。</p>
<hr>
</div></section><footer class="footer-container"><div class="footer-body"><img src="//img.alicdn.com/tfs/TB1dGrSwVT7gK0jSZFpXXaTkpXa-4802-1285.png"/><p class="docsite-power">website powered by docsite</p><div class="cols-container"><div class="col col-12"><h3>愿景</h3><p>Seata 是一款阿里巴巴开源的分布式事务解决方案，致力于在微服务架构下提供高性能和简单易用的分布式事务服务。</p></div><div class="col col-6"><dl><dt>文档</dt><dd><a href="/zh-cn/docs/overview/what-is-seata.html" target="_self">Seata 是什么？</a></dd><dd><a href="/zh-cn/docs/user/quickstart.html" target="_self">快速开始</a></dd><dd><a href="https://github.com/seata/seata.github.io/issues/new" target="_self">报告文档问题</a></dd><dd><a href="https://github.com/seata/seata.github.io" target="_self">在Github上编辑此文档</a></dd></dl></div><div class="col col-6"><dl><dt>资源</dt><dd><a href="/zh-cn/blog/index.html" target="_self">博客</a></dd><dd><a href="/zh-cn/community/index.html" target="_self">社区</a></dd></dl></div></div><div class="copyright"><span>Copyright © 2019 Seata</span></div></div></footer></div></div>
	<script src="https://f.alicdn.com/react/15.4.1/react-with-addons.min.js"></script>
	<script src="https://f.alicdn.com/react/15.4.1/react-dom.min.js"></script>
	<script>
		window.rootPath = '';
  </script>
	<script src="/build/documentation.js"></script>
	<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?104e73ef0c18b416b27abb23757ed8ee";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
    </script>
</body>
</html>
